package view;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.*;
 

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;



/**
 * Servlet implementation class WaitForFileServlet
 */

public class WaitForFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;	// optional
   private int maxMemSize = 4 * 1024; // optional
   private File file ;

   /**
    * @see HttpServlet#HttpServlet()
    */
   public WaitForFileServlet() {
       super();
       // TODO Auto-generated constructor stub
   }
   
   public void init( ){
      // Get the file location where it would be stored.
      filePath =  getServletContext().getInitParameter("file-upload");
      if(null==filePath)
    	  filePath="";
   }  

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");

        
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	      // Check that we have a file upload request
	      isMultipart = ServletFileUpload.isMultipartContent(request);
	      response.setContentType("text/html");
	      java.io.PrintWriter out = response.getWriter( );
	      if( !isMultipart ){
	         out.println("<html>");
	         out.println("<head>");
	         out.println("<title>Servlet upload</title>");  
	         out.println("</head>");
	         out.println("<body>");
	         out.println("<p>No file uploaded</p>"); 
	         out.println("</body>");
	         out.println("</html>");
	         return;
	      }
	      DiskFileItemFactory factory = new DiskFileItemFactory();
	      // maximum size that will be stored in memory
	      //factory.setSizeThreshold(maxMemSize); // optional
	      // Location to save data that is larger than maxMemSize.
	      //factory.setRepository(new File("c:\\temp")); // optional

	      // Create a new file upload handler
	      ServletFileUpload upload = new ServletFileUpload(factory);
	      // maximum file size to be uploaded.
	      //upload.setSizeMax( maxFileSize );

	      try{ 
	      // Parse the request to get file items.
	      List<FileItem> fileItems = upload.parseRequest(request);
	      // Process the uploaded file items
	      Iterator<FileItem> i = fileItems.iterator();

	      out.println("<html>");
	      out.println("<head>");
	      out.println("<title>Servlet upload</title>");  
	      out.println("</head>");
	      out.println("<body>");
	      while ( i.hasNext () ) 
	      {
	         FileItem fi = i.next();
	         if ( !fi.isFormField () )	
	         {
	            // Get the uploaded file parameters
	            String fieldName = fi.getFieldName();
	            String fileName = fi.getName();
	            String contentType = fi.getContentType();
	            boolean isInMemory = fi.isInMemory();
	            long sizeInBytes = fi.getSize();
	            // Write the file
	            if( fileName.lastIndexOf("\\") >= 0 ){
	               file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
	            }else{
	               file = new File( filePath +  fileName.substring(fileName.lastIndexOf("\\")+1)) ;
	            }
	           // fi.write( file ) ; // optional - writes in memory (mapped file) if its size is less than maxMemSize  

	            // physical write, please use buffer for this...
	            InputStream in=fi.getInputStream();
	            FileOutputStream outf=new FileOutputStream("c:\\temp\\"+fileName);
	            int data;
	            while((data=in.read())!=-1){
	            	outf.write(data);
	            }
	            in.close();
	            outf.close();
	            
	            out.println("Uploaded Filename: " + fileName + "<br>");
	         }
	      }
	      out.println("</body>");
	      out.println("</html>");
	   }catch(Exception ex) {
	       System.out.println(ex);
	   }


	}

}
